package com.movieknight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import android.content.Context;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.github.savvasdalkitsis.jtmdb.Movie;
import com.movieknight.Friend;

// FriendsActivity manages the user's friends.

public class FriendsActivity extends ListActivity {
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	private List<Friend> data;
	private ListView listView;
	private FriendListAdapter adapter;
	private SQLFriendsDataSource datasource;
	Context context;

	// Return values.
    static final int ADD_FRIEND_REQUEST = 0;
    static final int DELETE_FRIEND_REQUEST = 1;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friends);
        data = new ArrayList<Friend>();
		context = getApplicationContext();

        datasource = new SQLFriendsDataSource(this);
        datasource.open();
        refreshFriends();
        /*data = datasource.getAllFriends();
        
        
		adapter = new FriendListAdapter(this, data);
		setListAdapter(adapter);

		listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);*/
    }
	
	public void onButtonClick(View v) throws IOException {
		switch (v.getId()) {
		case R.id.viewCheckedItemsButton:
			showSelectedFriends();
			break;
		case R.id.toggleChoiceModeButton:
			toggleChoiceMode();
			break;
		}
	}
	
	private void toggleChoiceMode() {
		clearSelection();
	}
	
	
	private void showSelectedFriends() throws IOException {
		// Get an array that tells us for each position whether the item is
		// checked or not
		// --
		final SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
		if (checkedItems == null) {
			Toast.makeText(this, "No selection info available",
					Toast.LENGTH_LONG).show();
			return;
		}
		
		String FILENAME = "group";
		deleteFile(FILENAME);
		FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

		// For each element in the status array
		// --		
		boolean isFirstSelected = true;
		final int checkedItemsCount = checkedItems.size();
		final StringBuffer sb = new StringBuffer("Saved: ");
		String name;
		for (int i = 0; i < checkedItemsCount; ++i) {
			// This tells us the item position we are looking at
			// --
			final int position = checkedItems.keyAt(i);

			// This tells us the item status at the above position
			// --
			final boolean isChecked = checkedItems.valueAt(i);

			if (isChecked) {
				if (!isFirstSelected) {
					sb.append(", ");
				}
				name = data.get(position).getName();
				name = name + '\n';
				fos.write(name.getBytes());
				sb.append(data.get(position).getName());
				isFirstSelected = false;
			}
		}
		Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
		fos.close();
	}
	
	private void showSelectedFriendIds() {
		final StringBuffer sb = new StringBuffer("Selection: ");

		// Get an array that contains the IDs of the list items that are checked
		// --
		final long[] checkedItemIds = listView.getCheckItemIds();
		if (checkedItemIds == null) {
			Toast.makeText(this, "No selection", Toast.LENGTH_LONG).show();
			return;
		}

		// For each ID in the status array
		// --
		boolean isFirstSelected = true;
		final int checkedItemsCount = checkedItemIds.length;
		for (int i = 0; i < checkedItemsCount; ++i) {
			if (!isFirstSelected) {
				sb.append(", ");
			}
			sb.append(checkedItemIds[i]);
			isFirstSelected = false;
		}

		// Show a message with the country IDs that are selected
		// --
		Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
	}
	
	private void clearSelection() {
		final int itemCount = listView.getCount();
		for (int i = 0; i < itemCount; ++i) {
			listView.setItemChecked(i, false);
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.friends_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.addFriend:
			startActivityForResult(new Intent(FriendsActivity.this, AddFriendSearchBrowser.class), ADD_FRIEND_REQUEST);
			return true;
		case R.id.deleteFriend:
			if(data.size() != 0) {
				startActivityForResult(new Intent(FriendsActivity.this, FriendDeleteActivity.class), DELETE_FRIEND_REQUEST);
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent passedData) {
		if(requestCode == ADD_FRIEND_REQUEST) {
			if(resultCode == RESULT_OK) {
				// SERVER: Add friend using name String: passedData.getExtras().getString("returnKey1")
				Socket server = ((MovieKnightApp) this.getApplication()).getServer();
				String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
				int tempError = -1;
				PrintWriter out = null;
				try {
					out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
				
				out.println("{\"module\": \"movies\", \"method\": \"add_friend\",\"session_id\": \"" + sessionID + "\", \"params\": {\"friend_username\": \"" + passedData.getExtras().getString("returnKey1") + "\"}}");
				
				BufferedReader input;
				String st = null;
		        input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
				st = input.readLine();//Get Response from Server		
				JSONObject jsonObject = null;	
				
				//Parse response
				try {
					jsonObject = new JSONObject(st);
				
			
					//Error Code
					tempError = Integer.parseInt(jsonObject.getString("error_code"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//END SERVER ------------------------------------------------------
				
				if(tempError == 0)
				{
					refreshFriends();
					/*datasource.createFriend(passedData.getExtras().getString("returnKey1"));
	    			data = datasource.getAllFriends();
	    			adapter = new FriendListAdapter(this, data);
	    			setListAdapter(adapter);
	
	    			listView = getListView();
	    			listView.setItemsCanFocus(false);
	    			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);*/
				}
				else {
					Toast.makeText(context, getString(R.string.mainNoResult),
							Toast.LENGTH_SHORT).show();
				}
			}
		}
		if(requestCode == DELETE_FRIEND_REQUEST) {
			if(resultCode == RESULT_OK) {
    			refreshFriends();
				/*data = datasource.getAllFriends();
    			adapter = new FriendListAdapter(this, data);
    			setListAdapter(adapter);

    			listView = getListView();
    			listView.setItemsCanFocus(false);
    			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);*/
			}
		}
	}
	
	public void onResume(){
		super.onResume();
			//refreshFriends();
	}

	
	public void refreshFriends(){
		// SERVER: Refresh Friends List
					if(data!=null)
						data.clear();
					Socket server = ((MovieKnightApp) this.getApplication()).getServer();
					String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
					int tempError = -1;
							
					PrintWriter out = null;
					try {
						out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);	
						out.println("{\"module\": \"movies\", \"method\": \"get_friends\",\"session_id\": \"" + sessionID + "\"}");
								
						BufferedReader input = null;
						String st = null;
						input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
						st = input.readLine();//Get Response from Server		
						JSONObject jsonObject = null;
						JSONArray jsonArray = null;
							
						//Parse response
						try {
							jsonObject = new JSONObject(st);
							jsonArray = jsonObject.getJSONArray("friends");
						
							//Error Code
							tempError = Integer.parseInt(jsonObject.getString("error_code"));
							
						//END SERVER ------------------------------------------------------
						
						if(tempError ==0)
						{
							for(int i = 0; i < jsonArray.length(); i++){
								Friend tempFriend = new Friend((long)i,jsonArray.getString(i));
								data.add(i,tempFriend);
								Log.v("friend", jsonArray.getString(i));
							}
							
			    			adapter = new FriendListAdapter(this, data);
			    			setListAdapter(adapter);

			    			listView = getListView();
			    			listView.setItemsCanFocus(false);
			    			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
						}
						
						} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	}
}